import com.gargoylesoftware.htmlunit.Page
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.HtmlPage
import com.gargoylesoftware.htmlunit.SgmlPage
import com.gargoylesoftware.htmlunit.HttpWebConnection
import com.gargoylesoftware.htmlunit.WebResponse

import com.gargoylesoftware.htmlunit.HttpMethod
import java.util.concurrent.Semaphore
import com.gargoylesoftware.htmlunit.WebRequestSettings
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
import org.apache.commons.pool.ObjectPool
import org.apache.commons.pool.impl.StackObjectPool
/**
 * Created by IntelliJ IDEA.
 * User: AlexandruA
 * Date: 6/22/11
 * Time: 11:40 AM
 * To change this template use File | Settings | File Templates.
 */
class BugzillaConnection {
    //TODO create a pool of webClients

    private static BugzillaConnection connection = null;
    private poolSize = 5;
//    private static Vector<BugzillaConnection> connections = new Vector<BugzillaConnection>(poolSize);
//    private static Semaphore semaphore = new Semaphore(poolSize)
    private ObjectPool pool;

    private BugzillaConnection(ObjectPool pool, int size) {
        this.pool = pool;
        this.poolSize = size;
    }

    public static BugzillaConnection getInstance() {
        synchronized (this) {
            if (connection == null) {
                connection = new BugzillaConnection(new StackObjectPool(new BugzillaConnectionPoolFactory()), 5);
            } else {
                return connection;
            }
        }

//        semaphore.acquire();
//        synchronized (this) {//connections.isEmpty() && connections.remove(0) should be synchronized
//            if (connections.isEmpty()) {
//                def connection = new BugzillaConnection();
//                connection.webClient.setCssEnabled(false);
//                connection.webClient.setWebConnection(new HttpWebConnection(connection.webClient) {
//                    WebResponse getResponse(WebRequestSettings webRequest) {
//                        System.out.println(" url = " + webRequest.url + webRequest.requestParameters);
//                        return super.getResponse(webRequest);
//                    }
//                });
//                connections.add(connection);
//            }
//            return connections.remove(0);
//        }
    }

    private Page getPage(WebRequestSettings webRequest) {
        def page
        def webClient
        try {
            webClient = ((WebClient) pool.borrowObject());
            page = webClient.getPage(webRequest);
            if (page instanceof HtmlPage && page.titleText.contains('Log in')) {
//                page = authenticateToBugzilla(page);
            }
        } catch (Exception e) {
            throw new RuntimeException("Unable to borrow webClient from pool" +
                    e.toString());
        } finally {
            try {
                if (null != webClient) {
                    pool.returnObject(webClient);
                }
            } catch (Exception e) {
                println "cannot return webClient to pool " + e
            }
        }
        return page;
    }

    private Page authenticateToBugzilla(Page page) {
        println 'Trying to log In'
        def loginForm = page.getFormByName('login')
        def userField = loginForm.getInputByName("Bugzilla_login");
        def pwField = loginForm.getInputByName("drowssap_allizguB".reverse())
        userField.setValueAttribute("ionu@edifecs.com")
        pwField.setValueAttribute('knurdtuodessap'.reverse())
        def button = loginForm.getInputByValue("Log in");
        page = button.click();
        println "Loged In..."
        return page;
    }

    public SgmlPage createRequest(String url, QueryString queryString, HttpMethod submitMethod) {
        def thisUrl = new URL(url);
        WebRequestSettings webRequest = new WebRequestSettings(thisUrl, submitMethod);
        webRequest.setRequestParameters(queryString.getParams());
        def page = getPage(webRequest);
        return page
    }

//    private void releaseConnection() {
//        connections.add(this);
//        semaphore.release();
//    }

}
